﻿using CefSharp.DevTools.CSS;
using CefSharp.DevTools.Emulation;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using CommunityToolkit.Mvvm.Messaging;
using CommunityToolkit.Mvvm.Messaging.Messages;
using HsServerHa.Entity;
using HsServerHa.Entity.Models.SqlserverMirror;
using HsServerHa.UserControls.SqlserverMirrorControls;
using HsServerHa.UserControls.SqlserverMirrorControls.CommandProcessings;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Threading;

namespace HsServerHa.ViewModel.SqlserverMirrorViewModel
{


    public class CommandProcessingViewModel : ObservableObject
    {

        public CommandProcessingViewModel()
        {

            OperateCommands = ParameterSettings.OperateCommandBases;
            BeginOperate = new RelayCommand(Operate);
            OperateButtonContext = "开始执行";
            LogTextBox = new ObservableCollection<string>();
            WeakReferenceMessenger.Default.Register<ValueChangedMessage<string>, string>(this, "AddLog", (r, message) =>
            {
                if (message != null)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        LogTextBox.Add(message.Value);
                        logList.Add(new LogItem() { ShowText = message.Value, ShowColor = Brushes.Black, FontSize = 12 });

                    });
                }
            });

            WeakReferenceMessenger.Default.Register<ValueChangedMessage<bool>, string>(this, "Loading", (r, message) =>
            {
                if (message != null)
                {
                    Application.Current.Dispatcher.Invoke(() =>
                    {
                        LoadingIsActived = message.Value;
                    });
                    OperateButtonIsEnabled = !message.Value;
                    WeakReferenceMessenger.Default.Send(new ValueChangedMessage<bool>(!message.Value), "BackwardPageBtnIsEnable");

                }
            });
        }

        ObservableCollection<OperateCommandBase> _commands { get; set; }

        public RelayCommand BeginOperate { get; set; }

        /// <summary>
        /// 命令
        /// </summary>
        public ObservableCollection<OperateCommandBase> OperateCommands
        {
            get { return _commands; }
            set
            {
                _commands = value;
                OnPropertyChanged("OperateCommands");
            }
        }
        private ObservableCollection<string> logTextBox = new ObservableCollection<string>();
        private ObservableCollection<LogItem> logList = new ObservableCollection<LogItem>();

        public ObservableCollection<string> LogTextBox
        {
            get { return logTextBox; }
            set
            {
                logTextBox = value;
                OnPropertyChanged(nameof(LogTextBox));
            }
        }
        public ObservableCollection<LogItem> LogList
        {
            get { return logList; }
            set
            {
                logList = value;
                OnPropertyChanged(nameof(LogList));
            }
        }
        /// <summary>
        /// 当前命令执行到的步骤
        /// </summary>
        public OperateCommand OperateCommand { get; set; }

        public static bool IsAutoCopy { get; set; } = true;


        string operateButtonContext { get; set; }

        public string OperateButtonContext
        {
            get { return operateButtonContext; }
            set
            {
                operateButtonContext = value;
                OnPropertyChanged("OperateButtonContext");
            }
        }

        private int _progress;

        public int Progress
        {
            get { return _progress; }
            set
            {
                if (_progress != value)
                {
                    _progress = value;
                    OnPropertyChanged("Progress");
                }
            }
        }
       

        public bool operateButtonIsEnabled { get; set; } = true;

        public bool OperateButtonIsEnabled
        {
            get { return operateButtonIsEnabled; }
            set
            {
                operateButtonIsEnabled = value;
                OnPropertyChanged("OperateButtonIsEnabled");
            }
        }

        bool resetCommandIsEnabled;

        public bool ResetCommandIsEnabled
        {
            get { return resetCommandIsEnabled; }
            set
            {
                resetCommandIsEnabled = value;
                OnPropertyChanged("ResetCommandIsEnabled");
            }
        }

        bool loadingIsActived;

        public bool LoadingIsActived
        {
            get { return loadingIsActived; }
            set
            {
                loadingIsActived = value;
                OnPropertyChanged("LoadingIsActived");
            }
        }
        public OperateCommandBase CurOperateCommandBase;

        /// <summary>
        /// 执行操作命令
        /// </summary>
        public async void Operate()
        {
            Progress = 0;          
            int totalCount = _commands.Count;
            int finishCount = 0;
            foreach (var command in _commands.Where(s => s.OperateResult == false))//.Where(s => s.OperateResult == false))
            {
              
                try
                {
                    CurOperateCommandBase = command;
                    LoadingIsActived = true;
                    while (command.OperateCommand != OperateCommand.Compelete)
                    {
                        await command.operate(LogTextBox, ParameterSettings.FolderPath, IsAutoCopy);
                    }
                    LoadingIsActived = false;
                    command.OperateResult = true;
                    logList.Add(new LogItem() { ShowText = $"数据库【{command.DataBaseName}】镜像配置成功", ShowColor = Brushes.Green, FontSize = 13 });
                   
                }
                catch (Exception ex)
                {
                    if (ex.Message.Length > 40)
                    {
                        logList.Add(new LogItem() { ShowText = ex.Message.Substring(0, 40), ShowColor = Brushes.Blue, FontSize = 13 });
                        logList.Add(new LogItem() { ShowText = ex.Message.Substring(40), ShowColor = Brushes.Blue, FontSize = 13 });
                    }
                    else
                    {
                        logList.Add(new LogItem() { ShowText = ex.Message, ShowColor = Brushes.Blue, FontSize = 13 });
                    }


                }
                finally
                {
                    OperateCommand = command.OperateCommand;
                    OperateButtonContextSet(_commands.Last() == command);
                    finishCount++;
                }
                // 计算并更新进度条
                int progress = (int)((finishCount * 100) / totalCount);
                Progress = progress;
                

            }
        }

        /// <summary>
        /// 按钮控制
        /// </summary>
        /// <param name="isLast"></param>
        public void OperateButtonContextSet(bool isLast)
        {
            OperateButtonIsEnabled = true;
            switch (OperateCommand)
            {
                case OperateCommand.Begin:
                    OperateButtonContext = "开始执行";
                    break;
                case OperateCommand.WaitCopyBackUp:
                case OperateCommand.WaitSetMainPartner:
                case OperateCommand.WaitSetSlaverPartner:
                    OperateButtonContext = "继续";
                    break;
                case OperateCommand.Compelete:

                    if (isLast)
                    {
                        OperateButtonContext = "完成";
                        OperateButtonIsEnabled = false;
                    }
                    else
                    {
                        OperateButtonContext = "继续";
                    }
                    break;
                default:
                    break;
            };
        }

    }
}
